<template>
  <view class="leave-application">
    <!-- 表单内容 -->
    <view class="form-box">
      <!-- 请假类型 -->
      <view class="form-item form-item-picker required">
        <text class="label">请假类型</text>
        <!-- <picker class="picker" mode="selector" :range="categoryList" @change="onCategoryChange"> -->
        <view class="picker">
          <view class="picker-inner" @click="showCategoryPicker">
            <text class="picker-content">
              <img
                class="pickerIcon"
                src="/static//image/calendar.png"
                style="
                  position: relative;
                  bottom: -8rpx;
                  width: 38rpx;
                  padding-right: 10rpx;
                "
                alt=""
              />
              <text>{{ selectedCategory.label || "请选择类型" }}</text>
            </text>
            <uv-icon name="arrow-down" color="#47C28B" size="19"></uv-icon>
          </view>
        </view>
        <!-- </picker> -->
      </view>

      <!-- 请假时间 -->
      <view class="form-item form-item-picker required">
        <text class="label">请假时间</text>
        <view class="picker" mode="date" @click="handleTime">
          <view class="picker-inner">
            <text class="picker-content">
              <img
                class="pickerIcon"
                src="/static//image/calendar.png"
                style="
                  position: relative;
                  bottom: -8rpx;
                  width: 38rpx;
                  padding-right: 10rpx;
                "
                alt=""
              />
              <text v-if="range">{{ range }}</text>
              <text v-else>请选择类型</text>
            </text>
            <uv-icon name="arrow-down" color="#47C28B" size="19"></uv-icon>
          </view>
        </view>
      </view>

      <!-- 时长/天数 -->
      <view class="form-item required">
        <text class="label">Duration/days</text>
        <!-- <uv-input class="input" placeholder="According to the selection of display time" border="surround" v-model="day"></uv-input> -->
        <input
          @blur="handleDays"
          type="number"
          class="input"
          v-model="day"
          style="width: auto"
          placeholder="According to the selection of display time"
        />
      </view>

      <uv-calendars
        :title="['Leave Duration', 'Select Leave Duration']"
        :date="range"
        ref="calendars"
        color="#17A364"
        @confirm="confirm"
      />
      <!-- 请假事由 -->
      <view class="form-item">
        <text class="label">请假事由</text>
        <textarea
          v-model="content"
          class="textarea"
          style="width: auto"
          placeholder="请输入请假事由"
        />
      </view>

      <!-- 图片上传 -->
      <view class="form-item">
        <text class="label"
          >图片 <text class="tip required">最多上传9张</text></text
        >
        <uv-upload
          action="/api/common/upload"
          @afterRead="handleAfterRead"
          :fileList="fileList"
          name="3"
          multiple
          :maxCount="9"
          :previewFullImage="true"
          @delete="handleDelete"
        >
          <div class="uploadIcon">
            <uv-icon name="plus"></uv-icon>
          </div>
        </uv-upload>
      </view>

      <!-- 审批人 -->
      <view class="form-item required">
        <text class="label">审批人</text>
        <!-- <view class="approver-add" @tap="addApprover">
                    <uv-icon name="plus" size="20"></uv-icon>
                </view> -->
        <view class="approver-list">
          <uv-steps current="-1" inactiveColor="#A2E0C4" dot direction="column">
            <uv-steps-item
              class="steps-item"
              v-for="(item, index) in stepsList"
              :key="index"
            >
              <template v-slot:title>
                <view class="stepsName">
                  <text style="margin-right: 5px">{{ item.name }}</text>
                  <!-- <uv-icon name="close" color="#fff"></uv-icon> -->
                </view>
              </template>
            </uv-steps-item>
          </uv-steps>
          <view
            v-for="(person, idx) in approvers"
            :key="idx"
            class="approver-item"
          >
            <text>{{ person }}</text>
          </view>
        </view>
      </view>
      <uv-popup ref="popup" @change="change">
        <view
          style="width: 350rpx; height: calc(100vh - 88rpx); overflow-y: scroll"
        >
          <uv-list>
            <uv-list-item
              v-for="(item, index) in 50"
              :key="index"
              :title="`列表${index}`"
              thumb="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-dc-site/460d46d0-4fcc-11eb-8ff1-d5dcf8779628.png"
              thumb-size="lg"
            >
            </uv-list-item>
            <!-- <uv-list-item :show-extra-icon="true" :extra-icon="{icon:'photo',color:'red'}" title="列表左侧带扩展图标">
                        </uv-list-item> -->
          </uv-list>
        </view>
      </uv-popup>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-btns">
      <!-- 编辑 -->
      <template v-if="id">
        <button class="btn save" @tap="goBack">Cancel</button>
        <button class="btn submit" @tap="onSubmit(1)">Submit</button>
        <!-- <button class="btn submit" @tap="onSubmit(1)">withdraw</button> -->
      </template>
      <!-- 新增 -->
      <template v-else>
        <button class="btn save" @tap="onSubmit(0)">Save for release</button>
        <button class="btn submit" @tap="onSubmit(1)">Submit</button>
      </template>
    </view>

    <uv-popup
      ref="showphoneModal"
      @change="changePopup"
      round="20"
      :customStyle="{ overflow: 'initial' }"
    >
      <view class="forgot-modal" v-if="submitState == 1">
        <view class="modal-icon-box">
          <uv-icon
            class="modal-icon"
            size="56"
            color="#fff"
            name="lock-fill"
          ></uv-icon>
        </view>
        <view class="modal-title">Submit Leave</view>
        <view class="modal-tip">
          Double-check your leave details to ensure everything is correct. Do
          you want to proceed?
        </view>
        <button class="forgot-btn" @click="onSubmit(1)">Yes, Submit</button>
        <button
          class="cancel-btn"
          @click="
            () => {
              forgotPwdStatus = 2;
            }
          "
        >
          No, Let me check
        </button>
      </view>
      <view class="forgot-modal" v-if="submitState == 2">
        <view class="modal-icon-box">
          <uv-icon
            class="modal-icon"
            size="56"
            color="#fff"
            name="lock-fill"
          ></uv-icon>
        </view>
        <view class="modal-title">Leave Submitted!</view>
        <view class="modal-tip">
          Your leave request has been sent for review! Wait for HR to review
          your request.
        </view>
        <button class="forgot-btn" @click="handleHistory">
          View Expense History
        </button>
      </view>
    </uv-popup>
    <uv-popup
      ref="showCategory"
      :title="['Leave Category', 'Select Leave category']"
      round="20"
      :customStyle="{ overflow: 'initial' }"
    >
      <view class="category-popup">
        <view class="category-container">
          <view class="category-options">
            <view
              v-for="(option, index) in categoryList"
              :key="index"
              class="category-option"
              :class="{
                'category-option-selected':
                  selectedCategory.value == option.value,
              }"
              @click="selectAndConfirmCategory(option)"
            >
              <view class="category-option-text">{{ option.label }}</view>
            </view>
          </view>
          <view class="category-actions">
            <view class="category-close-btn" @click="closeCategoryPicker">
              Close
            </view>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import dayjs from "dayjs";
import { uploadFile } from "@/api/home";
import { getLeaveCategory, leaveApply, replacementDetail } from "@/api/replacement";
export default {
  data() {
    return {
      categoryList: ["事假", "病假", "年假", "调休"],
      selectedCategory: {
        value: 1,
        label: "事假",
      },
      selectedDate: "",
      submitState: 1,
      range: "",
      content: "",
      day: "1",
      calendarsMode: "range",
      result: {},
      images: [],
      stepsList: [
        { name: "和主管1", id: 1, state: 0 },
        { name: "和主管2", id: 2, state: 0 },
        { name: "和主管3", id: 3, state: 0 },
      ],
      fileList: [
        {
          url: "https://4dscene.4dage.com/new4dkk/images/case/szlsjs/home.png",
        },
        {
          url: "https://4dscene.4dage.com/new4dkk/images/case/cityAQ/home.png",
        },
        {
          url: "https://4dscene.4dage.com/new4dkk/images/case/zhcjda/home.png",
        },
      ],
      approvers: [],
    };
  },
  
  onLoad({ id, type }) {
    if (id) {
      this.id = id;
      replacementDetail({ id: id }).then((res) => {
        let approvalList = [res.user];
        if (res.audit_user) {
          approvalList.push(res.audit_user);
        }
        if (res.audit_user1) {
          approvalList.push(res.audit_user1);
        }
        this.detail = {
          ...res,
          approvalList,
        };
      });
    }
    this.type = type || 'askForLeave';
  },
  created() {
    this.range = uni.$uv.date(new Date().getTime(), "YYYY-MM-DD");
    getLeaveCategory({}).then((res) => {
      this.categoryList = res;
      this.selectedCategory = (res && res[0]) || {};
    });
  },
  methods: {
    confirm(e) {
      this.range = e.fulldate;
      console.log("this.range", this.range, e);
    },
    onCategoryChange(e) {
      this.selectedCategory = this.categoryList[e.detail.value];
    },
    onDateChange(e) {
      this.selectedDate = e.detail.value;
    },
    chooseImage() {
      // 选择图片逻辑
    },
    addApprover() {
      // 添加审批人逻辑
      this.$refs.popup.open("right");
    },
    async handleAfterRead(event) {
		console.log('afterRead',event)
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      const result = await uploadFile(event.file[0].url);
      this.fileList.push({
        url: result.full_path,
      });
    },
    onSave() {
      // 保存草稿逻辑
    },
    handleDays(e) {
      this.day = Math.abs((e.detail && e.detail.value) || 0);
      console.log("handleDays0", e);
    },
    showCategoryPicker() {
      this.$refs.showCategory.open("bottom");
    },
    selectAndConfirmCategory(category) {
      this.selectedCategory = category;
      this.$refs.showCategory.close();
    },
    handleTime() {
      this.calendarsMode = "range";
      this.$refs.calendars.open();
    },
    closeCategoryPicker() {
      this.$refs.showCategory.close();
    },
    onSubmit(val) {
      // 提交逻辑
      let that = this;
      this.submitState = 1;
      if (!this.day) {
        return uni.$uv.toast("According to the selection of display time");
      }
      leaveApply({
        days: this.day,
        start_time: dayjs(this.range).format("YYYY-MM-DD"),
        end_time: dayjs(this.range).add(this.day, "day").format("YYYY-MM-DD"),
        content: this.content,
        images: this.fileList.map((ele) => ele.url).join(","),
        category: this.selectedCategory.value,
      }).then((res) => {
        that.result = res;
        that.submitState = 2;

      });
      // this.$refs.showphoneModal.open('bottom')
    },
    handleHistory() {
      uni.$uv.route({
        type: "tab",
        url: "/pages/Approval/approval",
      });
    },
    changePopup({ show }) {
      let that = this;
      if (show) return;
      if (this.submitState === 2) {
        uni.$uv.route({
          url: "/pages/Approval/approvalDetail",
          params: {
            id: that.result.id,
          },
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.leave-application {
  background: #f8f9fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  display: flex;
  align-items: center;
  height: 56px;
  background: #fff;
  padding: 0 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);

  .back-btn {
    font-size: 22px;
    margin-right: 16px;
  }

  .title {
    font-size: 20px;
    font-weight: bold;
  }
}

.form-box {
  background: #fff;
  border-radius: 12px;
  margin: 15px 12px;
  padding: 23px 15px;
  flex: 1;

  .form-item {
    margin-bottom: 18px;

    .label {
      font-size: 15px;
      color: #333;
      margin-bottom: 6px;
      display: block;
    }

    .tip {
      color: #f56c6c;
      font-size: 12px;
      margin-left: 8px;
    }

    .picker,
    .input,
    .textarea {
      width: 100%;
      border: 1px solid #dcdfe6;
      border-radius: 6px;
      padding: 10px;
      font-size: 15px;
      background: #f7f8fa;
      margin-top: 6px;
    }

    .picker-inner {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .iconfont {
      font-size: 14px;
      color: #bbb;
    }

    .img-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 8px;

      .img-item,
      .img-upload {
        width: 64px;
        height: 64px;
        border: 1px dashed #dcdfe6;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fafbfc;
      }

      .img-item image {
        width: 100%;
        height: 100%;
        border-radius: 8px;
      }

      .plus {
        font-size: 32px;
        color: #bbb;
      }
    }

    .approver-add {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fafbfc;
      border-radius: 50%;
      border: 1px solid #98a2b3;

      .plus {
        font-size: 40rpx;
        color: #bbb;
      }
    }

    .approver-list {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 8px;

      .steps-item {
        padding: 15px 0;
      }

      .stepsName {
        background: #17a364;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-radius: 10px 10px 10px 10px;
        color: #fff;
        padding: 8px 15px;
      }

      .approver-item {
        background: #e6f7ff;
        color: #1890ff;
        border-radius: 50%;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
      }
    }
  }

  .required .label:before {
    content: "* ";
    color: #f56c6c;
  }
}

.category-container {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
  padding-bottom: 30rpx;
}

.category-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f2f2f2;
  text-align: center;
}

.category-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.category-options {
  padding: 0 23px 10rpx 23px;
  margin-bottom: 20rpx;
}

.category-option {
  display: flex;
  align-items: center;
  padding: 34rpx 24rpx;
  position: relative;
  transition: background-color 0.2s;
  margin-bottom: 8px;
  box-shadow: 0px 1 2px 0px rgba(16, 24, 40, 0.05);
  border-radius: 8px 8px 8px 8px;
  border: 1px solid #98a2b3;
}

.category-option:active {
  background-color: #f9f9f9;
}

.category-option-selected {
  border: 1px solid #19b36e;
  background-color: rgba(25, 179, 110, 0.1);
}

.category-option-selected::after {
  content: "";
  position: absolute;
  right: 30rpx;
  width: 36rpx;
  height: 36rpx;
  background-color: #19b36e;
  border-radius: 50%;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z'/%3E%3C/svg%3E");
  background-size: 24rpx;
  background-position: center;
  background-repeat: no-repeat;
}

.category-option-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: rgba(25, 179, 110, 0.1);
  margin-right: 20rpx;
}

.category-option-icon image {
  width: 40rpx;
  height: 40rpx;
}

.category-option-text {
  font-size: 26rpx;
  line-height: 38rpx;
  color: #333;
  flex: 1;
}

.category-actions {
  padding: 20rpx 30rpx;
}

.category-close-btn {
  margin: 0 30rpx;
  border: 1rpx solid #19b36e;
  color: #19b36e;
  font-size: 32rpx;
  font-weight: 500;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  text-align: center;
}

.category-submit-btn {
  display: none;
}
.uploadIcon {
  width: 80px;
  height: 80px;
  border: 1px dashed #dcdfe6;
  background: #fafbfc;
  border-radius: 20rpx;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>